package com.ruoyi.project.thirdservice.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.MapBuilder;
import com.ruoyi.common.utils.wxapi.WXCore;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.thirdservice.constant.WxConst;
import com.ruoyi.project.thirdservice.service.wx.entity.rundata.WxUserRunDataItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author yan
 */
@RestController
@RequestMapping("wx-api-data")
public class WxUserDataController {

    private static Logger logger = LoggerFactory.getLogger(WxUserDataController.class);

    @Value("${wx-api.sns.appid}")
    private String appid;
    @Value("${wx-api.sns.secret}")
    private String secret;

    /**
     * 小程序-获取用户步数
     *
     * @param encryptedData
     * @param iv
     * @return
     */
    @SuppressWarnings("all")
    @RequestMapping(value = "/getUserRunData", method = RequestMethod.GET)
    public AjaxResult getData(@RequestParam("encryptedData") String encryptedData
            , @RequestParam("iv") String iv, @RequestParam("sessionKey") String sessionKey
    ) {
        JSONObject theJSONObject = WXCore.decrypt(appid, encryptedData, sessionKey, iv);

        // 获取当前步数
        JSONArray runData = theJSONObject.getJSONArray(WxConst.STEP_INFO_LIST);
        if (CollectionUtils.isEmpty(runData)) {
            return AjaxResult.success(MapBuilder.create("data", 0).get());
        }

        WxUserRunDataItem theFirst = runData.
                getObject(runData.size() - 1, WxUserRunDataItem.class);
        return AjaxResult.success(MapBuilder.create("data", theFirst.getStep()).get());
    }
}
